<?php

declare(strict_types=1);

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

class Shipment extends Model
{
    use SoftDelete;

    protected $name = 'shipments';

    protected $autoWriteTimestamp = 'datetime';

    protected $json = ['extra_data'];

    protected $append = ['status_label'];

    public const STATUS_PENDING_PICKUP = 0;
    public const STATUS_PICKED_UP = 1;
    public const STATUS_IN_TRANSIT = 2;
    public const STATUS_DELIVERING = 3;
    public const STATUS_SIGNED = 4;
    public const STATUS_EXCEPTION = 5;
    public const STATUS_CANCELLED = 6;

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function company()
    {
        return $this->belongsTo(ShipmentCompany::class, 'company_id');
    }

    public function traces()
    {
        return $this->hasMany(ShipmentTrace::class, 'shipment_id');
    }

    public function assistUser()
    {
        return $this->belongsTo(User::class, 'assist_user_id');
    }

    public static function statusMap(): array
    {
        return [
            self::STATUS_PENDING_PICKUP => '待揽件',
            self::STATUS_PICKED_UP => '已揽件',
            self::STATUS_IN_TRANSIT => '运输中',
            self::STATUS_DELIVERING => '派送中',
            self::STATUS_SIGNED => '已签收',
            self::STATUS_EXCEPTION => '异常',
            self::STATUS_CANCELLED => '已取消',
        ];
    }

    public static function labelForStatus(int $status): string
    {
        return self::statusMap()[$status] ?? '未知状态';
    }

    public function getStatusLabelAttr(): string
    {
        return self::labelForStatus((int) $this->status);
    }
}
